//
//  KQMessageTextContentView.swift
//  JChat
//
//  Created by JIGUANG on 2017/3/9.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import YYText

open class KQMessageTextContentView: YYLabel, KQMessageContentViewType {
    private weak var _delegate: KQMessageDelegate?
    private var _message: KQMessageType!
    public override init(frame: CGRect) {
        super.init(frame: frame)
        _commonInit()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _commonInit()
    }

    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return super.canPerformAction(action, withSender: sender)
    }
    
    open func apply(_ message: KQMessageType) {
        guard let content = message.content as? KQMessageTextContent else {
            return
        }
        _delegate = content.delegate
        _message = message
        
        
        self.attributedText = content.text
        self.highlightTapAction = ({[weak self] containerView, text, range, rect in
            self!.didTapRichLabelText(self!, textRange: range)
        })
    }
    /**
     解析点击文字
     
     - parameter label:     YYLabel
     - parameter textRange: 高亮文字的 NSRange，不是 range
     */
    fileprivate func didTapRichLabelText(_ label: YYLabel, textRange: NSRange) {
        //解析 userinfo 的文字
        let attributedString = label.textLayout!.text
        if textRange.location >= attributedString.length {
            return
        }
        guard let hightlight: YYTextHighlight = attributedString.yy_attribute(YYTextHighlightAttributeName, at: UInt(textRange.location)) as? YYTextHighlight else {
            return
        }
        guard let info = hightlight.userInfo, info.count > 0 else {
            return
        }
    
        if let phone: String = info["phone"] as? String {
            _delegate?.tapCustom?(message: _message, nextType: .call, param: phone)

        }
        
        if let URL: String = info["URL"] as? String {
            _delegate?.tapCustom?(message: _message, nextType: .jumpWebView, param: URL)
        }
    }

    private func _commonInit() {
        self.numberOfLines = 0
    }
}

